//+------------------------------------------------------------------+
//|                                      Martingale_EA_Optimized.mq5 |
//|                                          Copyright 2024            |
//|                                               优化版马丁格尔EA       |
//+------------------------------------------------------------------+
#property copyright "Copyright 2024"
#property link ""
#property version "2.00"
#property description "优化版马丁格尔EA - 增强安全性和稳定性"

#include <Arrays/ArrayObj.mqh>
#include <Trade\Trade.mqh>
#include <Controls\Dialog.mqh>
#include <Controls\Label.mqh>
#include <Controls\Button.mqh>
#include <Controls\Edit.mqh>
#include "CustomDialog.mqh"

// 日志级别枚举
enum ENUM_LOG_LEVEL {
    LOG_LEVEL_ERROR = 0,
    LOG_LEVEL_WARNING = 1,
    LOG_LEVEL_INFO = 2,
    LOG_LEVEL_DEBUG = 3
};

// ============= 基础功能参数 =============
input group "============= 基础功能参数 ============="
input bool OpenTrend = false;            // 允许顺势加仓
input int MagicNumber = 123456;          // EA识别号
input int font_size = 8;                 // 字体大小
input ENUM_LOG_LEVEL LogLevel = LOG_LEVEL_INFO; // 日志级别

// ============= 资金管理参数 =============
input group "============= 资金管理参数 ============="
input double InitialLot = 0.01;          // 初始仓位
input double MaxRiskPercent = 0.02;       // 每笔交易最大风险百分比
input double MaxMarginUsage = 0.3;        // 最大保证金使用率
input double MinAccountBalance = 1000;    // 最小账户余额
input double MaxLeverage = 10;            // 最大杠杆倍数
input int MaxDailyTrades = 50;           // 日内最大交易次数

// ============= 加仓与手数相关参数 =============
input group "============= 加仓与手数相关参数 ============="
input double AtrRange = 0.8;             // 加仓atr的倍率
input double StepSize = 0;               // 手动输入的加仓步长(金额)
input int MaxOrderCount = 12;            // 最大订单数量
input double MultiplierOnLoss = 1.6;     // 亏损后倍数

// ============= 止盈止损相关参数 =============
input group "============= 止盈止损相关参数 ============="
input double StopProfit = 6;            // 平仓止盈金额（*订单数）
input double TakeProfitATR = 2;          // 止盈ATR倍数
input double StopLoss = -1500;           // 单方向止损
input double CloseAll = 1000;            // 总盈利达到目标平仓
input double MaxDrawdownPercent = 0.3;   // 最大回撤百分比

// ============= 时间与挂单相关参数 =============
input group "============= 时间与挂单相关参数 ============="
input int MaxBars = 500;                 // 最大搜索K线数
input double delta = 20;                 // 止盈增益点数
input double OrderDistanceATR = 0.1;     // 挂单距离ATR倍数
input int MaxTimeLimit = 5;              // 最大持仓时间限制(分钟)
input int MaxHoldingHours = 4;           // 最大持仓时间(小时)
input bool sj = false;                   // 是否启用时间控制
input int star = 0;                      // 开始时间（小时）
input int end = 24;                      // 结束时间（小时）

// ============= 交易方向与锁单相关参数 =============
input group "============= 交易方向与锁单相关参数 ============="
input bool Buy = true;                   // 允许买入
input bool Sell = true;                  // 允许卖出
input bool AllowLockPosition = true;     // 允许锁单

//+------------------------------------------------------------------+
//| 配置结构体                                                        |
//+------------------------------------------------------------------+
struct STradeConfig {
    double initialLot;
    double multiplier;
    int maxOrders;
    double stopLoss;
    double takeProfit;
    double maxRiskPercent;
    double maxMarginUsage;
    double minBalance;
    double maxLeverage;
    int maxDailyTrades;
    double maxDrawdownPercent;
    int maxHoldingHours;
};

//+------------------------------------------------------------------+
//| 指标缓存类                                                        |
//+------------------------------------------------------------------+
class CIndicatorCache {
private:
    datetime lastUpdate;
    double cachedATR;
    double cachedMA20;
    double cachedBBUpper;
    double cachedBBMiddle;
    double cachedBBLower;
    double cachedRSI;
    
    int atrHandle;
    int ma20Handle;
    int bbHandle;
    int rsiHandle;

public:
    CIndicatorCache() {
        lastUpdate = 0;
        cachedATR = 0;
        cachedMA20 = 0;
        cachedBBUpper = 0;
        cachedBBMiddle = 0;
        cachedBBLower = 0;
        cachedRSI = 0;
        
        atrHandle = INVALID_HANDLE;
        ma20Handle = INVALID_HANDLE;
        bbHandle = INVALID_HANDLE;
        rsiHandle = INVALID_HANDLE;
    }
    
    bool Initialize() {
        atrHandle = iATR(_Symbol, PERIOD_CURRENT, 14);
        ma20Handle = iMA(_Symbol, PERIOD_CURRENT, 20, 0, MODE_SMA, PRICE_CLOSE);
        bbHandle = iBands(_Symbol, PERIOD_CURRENT, 20, 0, 2.0, PRICE_CLOSE);
        rsiHandle = iRSI(_Symbol, PERIOD_CURRENT, 14, PRICE_CLOSE);
        
        return (atrHandle != INVALID_HANDLE && ma20Handle != INVALID_HANDLE && 
                bbHandle != INVALID_HANDLE && rsiHandle != INVALID_HANDLE);
    }
    
    void UpdateIndicators() {
        datetime currentTime = iTime(_Symbol, PERIOD_CURRENT, 0);
        if(currentTime == lastUpdate) return;
        
        double atrBuffer[1], ma20Buffer[1], bbUpperBuffer[1], bbMiddleBuffer[1], bbLowerBuffer[1], rsiBuffer[1];
        
        if(CopyBuffer(atrHandle, 0, 0, 1, atrBuffer) > 0) cachedATR = atrBuffer[0];
        if(CopyBuffer(ma20Handle, 0, 0, 1, ma20Buffer) > 0) cachedMA20 = ma20Buffer[0];
        if(CopyBuffer(bbHandle, 1, 0, 1, bbUpperBuffer) > 0) cachedBBUpper = bbUpperBuffer[0];
        if(CopyBuffer(bbHandle, 0, 0, 1, bbMiddleBuffer) > 0) cachedBBMiddle = bbMiddleBuffer[0];
        if(CopyBuffer(bbHandle, 2, 0, 1, bbLowerBuffer) > 0) cachedBBLower = bbLowerBuffer[0];
        if(CopyBuffer(rsiHandle, 0, 0, 1, rsiBuffer) > 0) cachedRSI = rsiBuffer[0];
        
        lastUpdate = currentTime;
    }
    
    double GetATR() { UpdateIndicators(); return cachedATR; }
    double GetMA20() { UpdateIndicators(); return cachedMA20; }
    double GetBBUpper() { UpdateIndicators(); return cachedBBUpper; }
    double GetBBMiddle() { UpdateIndicators(); return cachedBBMiddle; }
    double GetBBLower() { UpdateIndicators(); return cachedBBLower; }
    double GetRSI() { UpdateIndicators(); return cachedRSI; }
    
    void Cleanup() {
        if(atrHandle != INVALID_HANDLE) { IndicatorRelease(atrHandle); atrHandle = INVALID_HANDLE; }
        if(ma20Handle != INVALID_HANDLE) { IndicatorRelease(ma20Handle); ma20Handle = INVALID_HANDLE; }
        if(bbHandle != INVALID_HANDLE) { IndicatorRelease(bbHandle); bbHandle = INVALID_HANDLE; }
        if(rsiHandle != INVALID_HANDLE) { IndicatorRelease(rsiHandle); rsiHandle = INVALID_HANDLE; }
    }
};

//+------------------------------------------------------------------+
//| 资金管理类                                                        |
//+------------------------------------------------------------------+
class CMoneyManager {
private:
    STradeConfig config;
    int dailyTradeCount;
    datetime lastTradeDate;

public:
    CMoneyManager() {
        dailyTradeCount = 0;
        lastTradeDate = 0;
    }
    
    void SetConfig(const STradeConfig &cfg) { config = cfg; }
    
    bool ValidateParameters() {
        if(config.initialLot < SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN)) {
            WriteLog(LOG_LEVEL_ERROR, "初始手数小于最小交易量");
            return false;
        }
        
        if(config.multiplier < 1.0 || config.multiplier > 3.0) {
            WriteLog(LOG_LEVEL_ERROR, "倍数应在1.0-3.0之间");
            return false;
        }
        
        if(config.maxOrders > 20) {
            WriteLog(LOG_LEVEL_WARNING, "最大订单数建议不超过20");
        }
        
        if(!AccountInfoInteger(ACCOUNT_TRADE_ALLOWED)) {
            WriteLog(LOG_LEVEL_ERROR, "账户不允许交易");
            return false;
        }
        
        if(AccountInfoDouble(ACCOUNT_BALANCE) < config.minBalance) {
            WriteLog(LOG_LEVEL_ERROR, StringFormat("账户余额不足%.0f，建议增加资金", config.minBalance));
            return false;
        }
        
        return true;
    }
    
    double CalculateSafeLotSize(int orderCount) {
        double accountBalance = AccountInfoDouble(ACCOUNT_BALANCE);
        double freeMargin = AccountInfoDouble(ACCOUNT_MARGIN_FREE);
        
        // 基于风险百分比的手数计算
        double maxLotByRisk = (accountBalance * config.maxRiskPercent) / 1000;
        
        // 基于可用保证金的手数计算
        double requiredMargin = SymbolInfoDouble(_Symbol, SYMBOL_MARGIN_INITIAL);
        double maxLotByMargin = (freeMargin * config.maxMarginUsage) / requiredMargin;
        
        // 马丁格尔手数计算
        double martingaleLot = NormalizeDouble(MathPow(config.multiplier, orderCount) * config.initialLot, 2);
        
        // 取最小值确保安全
        double safeLot = MathMin(martingaleLot, MathMin(maxLotByRisk, maxLotByMargin));
        
        // 确保不小于最小手数
        double minLot = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN);
        return MathMax(safeLot, minLot);
    }
    
    bool CanOpenMorePositions(double lotSize, double totalBuyLots, double totalSellLots) {
        // 检查账户余额
        double accountBalance = AccountInfoDouble(ACCOUNT_BALANCE);
        if(accountBalance < config.minBalance) {
            WriteLog(LOG_LEVEL_WARNING, "账户余额不足最小要求");
            return false;
        }
        
        // 检查保证金充足性
        double freeMargin = AccountInfoDouble(ACCOUNT_MARGIN_FREE);
        double requiredMargin = lotSize * SymbolInfoDouble(_Symbol, SYMBOL_MARGIN_INITIAL);
        if(freeMargin < requiredMargin * 3) {
            WriteLog(LOG_LEVEL_WARNING, "保证金不足，无法开仓");
            return false;
        }
        
        // 检查最大风险敞口
        double totalExposure = (totalBuyLots + totalSellLots + lotSize) * 100000;
        if(totalExposure > accountBalance * config.maxLeverage) {
            WriteLog(LOG_LEVEL_WARNING, "超出最大杠杆限制");
            return false;
        }
        
        // 检查当日交易次数
        datetime today = StringToTime(TimeToString(TimeCurrent(), TIME_DATE));
        if(today != lastTradeDate) {
            dailyTradeCount = 0;
            lastTradeDate = today;
        }
        if(dailyTradeCount >= config.maxDailyTrades) {
            WriteLog(LOG_LEVEL_WARNING, "超出日内最大交易次数");
            return false;
        }
        
        return true;
    }
    
    void IncrementDailyTradeCount() { dailyTradeCount++; }
    
    double CheckDrawdownRatio() {
        double accountBalance = AccountInfoDouble(ACCOUNT_BALANCE);
        double accountEquity = AccountInfoDouble(ACCOUNT_EQUITY);
        return (accountBalance - accountEquity) / accountBalance;
    }
    
    bool IsDrawdownExcessive() {
        return CheckDrawdownRatio() > config.maxDrawdownPercent;
    }
};

//+------------------------------------------------------------------+
//| 风险管理类                                                        |
//+------------------------------------------------------------------+
class CRiskManager {
private:
    STradeConfig config;
    datetime lastRiskCheck;

public:
    CRiskManager() { lastRiskCheck = 0; }
    
    void SetConfig(const STradeConfig &cfg) { config = cfg; }
    
    void CheckRiskMetrics(double buyTotalProfit, double sellTotalProfit, int buyOrderCount, int sellOrderCount) {
        if(TimeCurrent() - lastRiskCheck < 60) return; // 每分钟检查一次
        
        double accountBalance = AccountInfoDouble(ACCOUNT_BALANCE);
        double accountEquity = AccountInfoDouble(ACCOUNT_EQUITY);
        double drawdown = (accountBalance - accountEquity) / accountBalance;
        
        // 回撤警告
        if(drawdown > 0.2) {
            string alertMsg = StringFormat("警告：账户回撤达到 %.1f%%", drawdown * 100);
            Alert(alertMsg);
            WriteLog(LOG_LEVEL_WARNING, alertMsg);
        }
        
        // 订单数量警告
        int totalOrders = buyOrderCount + sellOrderCount;
        if(totalOrders > 10) {
            string alertMsg = StringFormat("警告：当前订单数 %d，风险较高", totalOrders);
            Alert(alertMsg);
            WriteLog(LOG_LEVEL_WARNING, alertMsg);
        }
        
        // 盈亏警告
        double totalProfit = buyTotalProfit + sellTotalProfit;
        if(totalProfit < -accountBalance * 0.1) {
            string alertMsg = StringFormat("警告：总亏损达到账户余额的%.1f%%", -totalProfit/accountBalance*100);
            Alert(alertMsg);
            WriteLog(LOG_LEVEL_WARNING, alertMsg);
        }
        
        lastRiskCheck = TimeCurrent();
    }
    
    bool ShouldLockPosition(ENUM_POSITION_TYPE posType, double currentLoss, datetime maxOrderTime) {
        // 多重确认机制
        bool lossThreshold = currentLoss < -1000;
        bool drawdownCheck = CheckDrawdownRatio() > config.maxDrawdownPercent;
        bool timeCheck = (maxOrderTime > 0) && ((TimeCurrent() - maxOrderTime) > 3600); // 持仓超过1小时
        
        // 至少满足2个条件才锁单
        int conditionCount = 0;
        if(lossThreshold) conditionCount++;
        if(drawdownCheck) conditionCount++;
        if(timeCheck) conditionCount++;
        
        return conditionCount >= 2;
    }
    
private:
    double CheckDrawdownRatio() {
        double accountBalance = AccountInfoDouble(ACCOUNT_BALANCE);
        double accountEquity = AccountInfoDouble(ACCOUNT_EQUITY);
        return (accountBalance - accountEquity) / accountBalance;
    }
};

//+------------------------------------------------------------------+
//| 持仓管理类                                                        |
//+------------------------------------------------------------------+
class CPositionManager {
private:
    CTrade trade;
    int maxRetries;
    int retryDelay;

public:
    CPositionManager() {
        maxRetries = 3;
        retryDelay = 1000;
        trade.SetExpertMagicNumber(MagicNumber);
        trade.LogLevel(0);
    }
    
    bool SafeTradeOperation(ENUM_ORDER_TYPE orderType, double lots, double price, string comment = "") {
        for(int i = 0; i < maxRetries; i++) {
            // 检查连接状态
            if(!TerminalInfoInteger(TERMINAL_CONNECTED)) {
                WriteLog(LOG_LEVEL_WARNING, "网络连接断开，等待重连...");
                Sleep(retryDelay);
                continue;
            }
            
            bool result = false;
            
            // 执行交易
            switch(orderType) {
                case ORDER_TYPE_BUY:
                    result = trade.Buy(lots, _Symbol, price, 0, 0, comment);
                    break;
                case ORDER_TYPE_SELL:
                    result = trade.Sell(lots, _Symbol, price, 0, 0, comment);
                    break;
                case ORDER_TYPE_BUY_STOP:
                    result = trade.BuyStop(lots, price, _Symbol, 0, 0, ORDER_TIME_GTC, 0, comment);
                    break;
                case ORDER_TYPE_SELL_STOP:
                    result = trade.SellStop(lots, price, _Symbol, 0, 0, ORDER_TIME_GTC, 0, comment);
                    break;
            }
            
            if(result) {
                WriteLog(LOG_LEVEL_INFO, StringFormat("交易成功：%s %.2f手 价格%.5f", 
                    EnumToString(orderType), lots, price));
                return true;
            }
            
            // 分析错误并决定是否重试
            int error = GetLastError();
            switch(error) {
                case TRADE_RETCODE_REQUOTE:
                case TRADE_RETCODE_PRICE_OFF:
                case TRADE_RETCODE_TIMEOUT:
                    WriteLog(LOG_LEVEL_WARNING, StringFormat("交易错误 %d，第 %d 次重试", error, i+1));
                    Sleep(retryDelay);
                    break;
                default:
                    WriteLog(LOG_LEVEL_ERROR, StringFormat("交易失败，错误代码: %d，不再重试", error));
                    return false;
            }
        }
        
        return false;
    }
    
    bool SafePositionClose(ulong ticket) {
        for(int i = 0; i < maxRetries; i++) {
            if(trade.PositionClose(ticket)) {
                WriteLog(LOG_LEVEL_INFO, StringFormat("平仓成功：票据 %d", ticket));
                return true;
            }
            
            int error = GetLastError();
            WriteLog(LOG_LEVEL_WARNING, StringFormat("平仓失败，票据: %d, 错误: %d, 尝试次数: %d", 
                ticket, error, i + 1));
            
            Sleep(retryDelay);
        }
        
        WriteLog(LOG_LEVEL_ERROR, StringFormat("平仓最终失败，票据: %d", ticket));
        return false;
    }
    
    bool SafeOrderDelete(ulong ticket) {
        for(int i = 0; i < maxRetries; i++) {
            if(trade.OrderDelete(ticket)) {
                WriteLog(LOG_LEVEL_INFO, StringFormat("删除挂单成功：票据 %d", ticket));
                return true;
            }
            
            Sleep(retryDelay);
        }
        
        WriteLog(LOG_LEVEL_ERROR, StringFormat("删除挂单失败，票据: %d", ticket));
        return false;
    }
    
    bool CloseAllPositions(int direction = 0, string batchId = "") {
        bool result = true;
        int retryCount = 0;
        
        while(retryCount < 10) {
            bool needMoreAttempts = false;
            
            for(int i = PositionsTotal() - 1; i >= 0; i--) {
                if(PositionSelectByTicket(PositionGetTicket(i))) {
                    if(PositionGetString(POSITION_SYMBOL) == Symbol() &&
                       PositionGetInteger(POSITION_MAGIC) == MagicNumber) {
                        
                        ENUM_POSITION_TYPE posType = (ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE);
                        ulong ticket = PositionGetTicket(i);
                        
                        bool shouldClose = false;
                        if(direction == 0) shouldClose = true;
                        else if(direction > 0 && posType == POSITION_TYPE_BUY) shouldClose = true;
                        else if(direction < 0 && posType == POSITION_TYPE_SELL) shouldClose = true;
                        
                        if(shouldClose) {
                            if(!SafePositionClose(ticket)) {
                                result = false;
                                needMoreAttempts = true;
                            }
                        }
                    }
                }
            }
            
            if(!needMoreAttempts) break;
            retryCount++;
            Sleep(1000);
        }
        
        return result;
    }
};

//+------------------------------------------------------------------+
//| 全局变量                                                          |
//+------------------------------------------------------------------+
STradeConfig g_config;
CIndicatorCache *g_indicators = NULL;
CMoneyManager *g_moneyManager = NULL;
CRiskManager *g_riskManager = NULL;
CPositionManager *g_positionManager = NULL;

// 交易统计变量
double buyTotalLots = 0, sellTotalLots = 0;
double buyTotalProfit = 0, sellTotalProfit = 0;
double buyAveragePrice = 0, sellAveragePrice = 0;
int buyOrderCount = 0, sellOrderCount = 0;
datetime maxBuyTime = 0, maxSellTime = 0;
double lowestBuyPrice = 0, highestSellPrice = 0;

// 锁单相关变量
bool g_isLocked = false;
bool g_isUnlocking = false;
ENUM_POSITION_TYPE g_lockType;
double g_lockProfit = 0;

//+------------------------------------------------------------------+
//| 日志函数                                                          |
//+------------------------------------------------------------------+
void WriteLog(ENUM_LOG_LEVEL level, string message) {
    if(level <= LogLevel) {
        string prefix = "";
        switch(level) {
            case LOG_LEVEL_ERROR: prefix = "[ERROR]"; break;
            case LOG_LEVEL_WARNING: prefix = "[WARN]"; break;
            case LOG_LEVEL_INFO: prefix = "[INFO]"; break;
            case LOG_LEVEL_DEBUG: prefix = "[DEBUG]"; break;
        }
        Print(prefix + " " + TimeToString(TimeCurrent()) + " " + message);
    }
}

//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit() {
    WriteLog(LOG_LEVEL_INFO, "正在初始化优化版马丁格尔EA...");
    
    // 初始化配置
    g_config.initialLot = InitialLot;
    g_config.multiplier = MultiplierOnLoss;
    g_config.maxOrders = MaxOrderCount;
    g_config.stopLoss = StopLoss;
    g_config.takeProfit = StopProfit;
    g_config.maxRiskPercent = MaxRiskPercent;
    g_config.maxMarginUsage = MaxMarginUsage;
    g_config.minBalance = MinAccountBalance;
    g_config.maxLeverage = MaxLeverage;
    g_config.maxDailyTrades = MaxDailyTrades;
    g_config.maxDrawdownPercent = MaxDrawdownPercent;
    g_config.maxHoldingHours = MaxHoldingHours;
    
    // 创建管理类实例
    g_indicators = new CIndicatorCache();
    g_moneyManager = new CMoneyManager();
    g_riskManager = new CRiskManager();
    g_positionManager = new CPositionManager();
    
    if(!g_indicators || !g_moneyManager || !g_riskManager || !g_positionManager) {
        WriteLog(LOG_LEVEL_ERROR, "创建管理类实例失败");
        return INIT_FAILED;
    }
    
    // 初始化各组件
    if(!g_indicators.Initialize()) {
        WriteLog(LOG_LEVEL_ERROR, "指标初始化失败");
        return INIT_FAILED;
    }
    
    g_moneyManager.SetConfig(g_config);
    g_riskManager.SetConfig(g_config);
    
    // 验证参数
    if(!g_moneyManager.ValidateParameters()) {
        WriteLog(LOG_LEVEL_ERROR, "参数验证失败");
        return INIT_FAILED;
    }
    
    WriteLog(LOG_LEVEL_INFO, "EA初始化成功");
    return INIT_SUCCEEDED;
}

//+------------------------------------------------------------------+
//| Expert tick function                                              |
//+------------------------------------------------------------------+
void OnTick() {
    static datetime lastUpdate = 0;
    static int lastBar = 0;
    
    datetime currentTime = iTime(_Symbol, PERIOD_CURRENT, 0);
    int currentBar = Bars(_Symbol, PERIOD_CURRENT);
    
    // 只在新K线时执行复杂计算
    if(currentTime != lastUpdate || currentBar != lastBar) {
        g_indicators.UpdateIndicators();
        lastUpdate = currentTime;
        lastBar = currentBar;
    }
    
    // 每tick都需要检查的项目
    CalculateOrderStats();
    
    // 风险检查
    g_riskManager.CheckRiskMetrics(buyTotalProfit, sellTotalProfit, buyOrderCount, sellOrderCount);
    
    // 如果回撤过大，停止交易
    if(g_moneyManager.IsDrawdownExcessive()) {
        WriteLog(LOG_LEVEL_WARNING, "回撤过大，停止交易");
        return;
    }
    
    // 检查锁单条件
    if(!g_isLocked && !g_isUnlocking && AllowLockPosition) {
        CheckLockCondition();
    }
    
    // 如果处于锁单状态，直接返回
    if(g_isLocked) {
        return;
    }
    
    // 处理止盈止损
    HandleTakeProfit();
    HandleStopLoss();
    
    // 交易逻辑
    if(!g_isUnlocking) {
        ProcessTradingLogic();
    } else {
        HandleBreakEven();
    }
}

//+------------------------------------------------------------------+
//| 计算订单统计信息                                                   |
//+------------------------------------------------------------------+
void CalculateOrderStats() {
    // 重置统计数据
    buyTotalLots = 0; sellTotalLots = 0;
    buyTotalProfit = 0; sellTotalProfit = 0;
    buyOrderCount = 0; sellOrderCount = 0;
    double buyTotalValue = 0, sellTotalValue = 0;
    double highestBuyPrice = 0;
    double lowestSellPrice = 0;
    
    // 遍历所有持仓
    for(int i = PositionsTotal() - 1; i >= 0; i--) {
        if(PositionSelectByTicket(PositionGetTicket(i))) {
            if(PositionGetString(POSITION_SYMBOL) == Symbol() &&
               PositionGetInteger(POSITION_MAGIC) == MagicNumber) {
                
                double posLots = PositionGetDouble(POSITION_VOLUME);
                double posPrice = PositionGetDouble(POSITION_PRICE_OPEN);
                double posProfit = PositionGetDouble(POSITION_PROFIT);
                double posSwap = PositionGetDouble(POSITION_SWAP);
                
                if(PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY) {
                    buyOrderCount++;
                    buyTotalLots += posLots;
                    buyTotalValue += posPrice * posLots;
                    buyTotalProfit += posProfit + posSwap;
                    
                    if(highestBuyPrice < posPrice || highestBuyPrice == 0) highestBuyPrice = posPrice;
                    if(lowestBuyPrice > posPrice || lowestBuyPrice == 0) lowestBuyPrice = posPrice;
                }
                else if(PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_SELL) {
                    sellOrderCount++;
                    sellTotalLots += posLots;
                    sellTotalValue += posPrice * posLots;
                    sellTotalProfit += posProfit + posSwap;
                    
                    if(highestSellPrice < posPrice || highestSellPrice == 0) highestSellPrice = posPrice;
                    if(lowestSellPrice > posPrice || lowestSellPrice == 0) lowestSellPrice = posPrice;
                }
            }
        }
    }
    
    // 计算平均价格
    if(buyTotalLots > 0) buyAveragePrice = NormalizeDouble(buyTotalValue / buyTotalLots, _Digits);
    if(sellTotalLots > 0) sellAveragePrice = NormalizeDouble(sellTotalValue / sellTotalLots, _Digits);
}

//+------------------------------------------------------------------+
//| 处理交易逻辑                                                       |
//+------------------------------------------------------------------+
void ProcessTradingLogic() {
    MqlTick latest_price;
    if(!SymbolInfoTick(_Symbol, latest_price)) return;
    
    double ask = latest_price.ask;
    double bid = latest_price.bid;
    double atr = g_indicators.GetATR();
    double ma20 = g_indicators.GetMA20();
    
    // 买入逻辑
    if(Buy && buyOrderCount < g_config.maxOrders && bid < ma20) {
        double lotSize = g_moneyManager.CalculateSafeLotSize(buyOrderCount);
        
        if(g_moneyManager.CanOpenMorePositions(lotSize, buyTotalLots, sellTotalLots)) {
            double price = (buyOrderCount == 0) ? ask + AtrRange * atr : lowestBuyPrice - AtrRange * atr;
            
            if(g_positionManager.SafeTradeOperation(ORDER_TYPE_BUY_STOP, lotSize, price, "Optimized Martingale Buy")) {
                g_moneyManager.IncrementDailyTradeCount();
                
                if(buyOrderCount >= g_config.maxOrders - 1) {
                    maxBuyTime = TimeCurrent();
                    WriteLog(LOG_LEVEL_INFO, "买单达到最大数量，记录时间");
                }
            }
        }
    }
    
    // 卖出逻辑
    if(Sell && sellOrderCount < g_config.maxOrders && ask > ma20) {
        double lotSize = g_moneyManager.CalculateSafeLotSize(sellOrderCount);
        
        if(g_moneyManager.CanOpenMorePositions(lotSize, buyTotalLots, sellTotalLots)) {
            double price = (sellOrderCount == 0) ? bid - AtrRange * atr : highestSellPrice + AtrRange * atr;
            
            if(g_positionManager.SafeTradeOperation(ORDER_TYPE_SELL_STOP, lotSize, price, "Optimized Martingale Sell")) {
                g_moneyManager.IncrementDailyTradeCount();
                
                if(sellOrderCount >= g_config.maxOrders - 1) {
                    maxSellTime = TimeCurrent();
                    WriteLog(LOG_LEVEL_INFO, "卖单达到最大数量，记录时间");
                }
            }
        }
    }
}

//+------------------------------------------------------------------+
//| 处理止盈平仓                                                       |
//+------------------------------------------------------------------+
void HandleTakeProfit() {
    // 检查买入止盈
    if(buyTotalProfit >= g_config.takeProfit * buyOrderCount && buyTotalLots > 0) {
        WriteLog(LOG_LEVEL_INFO, StringFormat("买入止盈触发，当前盈利: %.2f", buyTotalProfit));
        g_positionManager.CloseAllPositions(1, "TP-Buy");
    }
    
    // 检查卖出止盈
    if(sellTotalProfit >= g_config.takeProfit * sellOrderCount && sellTotalLots > 0) {
        WriteLog(LOG_LEVEL_INFO, StringFormat("卖出止盈触发，当前盈利: %.2f", sellTotalProfit));
        g_positionManager.CloseAllPositions(-1, "TP-Sell");
    }
    
    // 检查总盈利止盈
    double totalProfit = buyTotalProfit + sellTotalProfit;
    if(totalProfit >= CloseAll) {
        WriteLog(LOG_LEVEL_INFO, StringFormat("总盈利止盈触发，当前总盈利: %.2f", totalProfit));
        g_positionManager.CloseAllPositions(0, "TP-All");
    }
}

//+------------------------------------------------------------------+
//| 处理止损平仓                                                       |
//+------------------------------------------------------------------+
void HandleStopLoss() {
    // 检查买入止损
    if(buyTotalProfit <= g_config.stopLoss) {
        WriteLog(LOG_LEVEL_WARNING, StringFormat("买入止损触发，当前亏损: %.2f", buyTotalProfit));
        g_positionManager.CloseAllPositions(1, "SL-Buy");
    }
    
    // 检查卖出止损
    if(sellTotalProfit <= g_config.stopLoss) {
        WriteLog(LOG_LEVEL_WARNING, StringFormat("卖出止损触发，当前亏损: %.2f", sellTotalProfit));
        g_positionManager.CloseAllPositions(-1, "SL-Sell");
    }
}

//+------------------------------------------------------------------+
//| 检查锁单条件                                                       |
//+------------------------------------------------------------------+
void CheckLockCondition() {
    // 检查买单锁单条件
    if(g_riskManager.ShouldLockPosition(POSITION_TYPE_BUY, buyTotalProfit, maxBuyTime)) {
        string alertMessage = StringFormat("警告：买单锁单条件触发！当前亏损: %.2f", buyTotalProfit);
        Alert(alertMessage);
        WriteLog(LOG_LEVEL_WARNING, alertMessage);
        LockPosition(POSITION_TYPE_BUY);
        return;
    }
    
    // 检查卖单锁单条件
    if(g_riskManager.ShouldLockPosition(POSITION_TYPE_SELL, sellTotalProfit, maxSellTime)) {
        string alertMessage = StringFormat("警告：卖单锁单条件触发！当前亏损: %.2f", sellTotalProfit);
        Alert(alertMessage);
        WriteLog(LOG_LEVEL_WARNING, alertMessage);
        LockPosition(POSITION_TYPE_SELL);
        return;
    }
}

//+------------------------------------------------------------------+
//| 锁单函数                                                          |
//+------------------------------------------------------------------+
void LockPosition(ENUM_POSITION_TYPE posType) {
    if(g_isLocked) return;
    
    double lockLots = (posType == POSITION_TYPE_BUY) ? buyTotalLots : sellTotalLots;
    if(lockLots <= 0) return;
    
    ENUM_ORDER_TYPE lockOrderType = (posType == POSITION_TYPE_BUY) ? ORDER_TYPE_SELL : ORDER_TYPE_BUY;
    string lockComment = (posType == POSITION_TYPE_BUY) ? "sell_lock" : "buy_lock";
    
    MqlTick latest_price;
    if(!SymbolInfoTick(_Symbol, latest_price)) return;
    
    double price = (posType == POSITION_TYPE_BUY) ? latest_price.bid : latest_price.ask;
    
    if(g_positionManager.SafeTradeOperation(lockOrderType, lockLots, price, lockComment)) {
        g_isLocked = true;
        g_lockType = posType;
        g_lockProfit = 0;
        
        WriteLog(LOG_LEVEL_INFO, StringFormat("锁单成功 - 类型: %s 手数: %.2f", 
            EnumToString(posType), lockLots));
    }
}

//+------------------------------------------------------------------+
//| 解锁函数                                                          |
//+------------------------------------------------------------------+
void UnlockPosition() {
    if(!g_isLocked) return;
    
    // 查找并平掉锁单
    for(int i = PositionsTotal() - 1; i >= 0; i--) {
        if(PositionSelectByTicket(PositionGetTicket(i))) {
            string comment = PositionGetString(POSITION_COMMENT);
            if(StringFind(comment, "lock") >= 0) {
                ulong ticket = PositionGetTicket(i);
                if(g_positionManager.SafePositionClose(ticket)) {
                    g_lockProfit = PositionGetDouble(POSITION_PROFIT);
                    g_isLocked = false;
                    g_isUnlocking = true;
                    
                    WriteLog(LOG_LEVEL_INFO, StringFormat("解锁成功 - 收益: %.2f", g_lockProfit));
                    return;
                }
            }
        }
    }
}

//+------------------------------------------------------------------+
//| 处理保本平仓                                                       |
//+------------------------------------------------------------------+
void HandleBreakEven() {
    if(!g_isUnlocking) return;
    
    double currentProfit = (g_lockType == POSITION_TYPE_BUY) ? buyTotalProfit : sellTotalProfit;
    
    if(currentProfit + g_lockProfit > 0) {
        WriteLog(LOG_LEVEL_INFO, StringFormat("保本平仓触发 - 当前收益: %.2f 锁单收益: %.2f", 
            currentProfit, g_lockProfit));
        
        if(g_lockType == POSITION_TYPE_BUY) {
            g_positionManager.CloseAllPositions(1, "BE-Buy");
        } else {
            g_positionManager.CloseAllPositions(-1, "BE-Sell");
        }
        
        // 重置状态
        g_isUnlocking = false;
        g_isLocked = false;
        g_lockProfit = 0;
        maxBuyTime = 0;
        maxSellTime = 0;
    }
}

//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason) {
    WriteLog(LOG_LEVEL_INFO, "正在清理EA资源...");
    
    // 清理管理类实例
    if(g_indicators) { g_indicators.Cleanup(); delete g_indicators; g_indicators = NULL; }
    if(g_moneyManager) { delete g_moneyManager; g_moneyManager = NULL; }
    if(g_riskManager) { delete g_riskManager; g_riskManager = NULL; }
    if(g_positionManager) { delete g_positionManager; g_positionManager = NULL; }
    
    // 删除图形对象
    ObjectsDeleteAll(0, "Martingale_");
    
    WriteLog(LOG_LEVEL_INFO, "EA清理完成");
}

//+------------------------------------------------------------------+
//| 交易事务处理                                                       |
//+------------------------------------------------------------------+
void OnTradeTransaction(const MqlTradeTransaction &trans,
                        const MqlTradeRequest &request,
                        const MqlTradeResult &result) {
    if(trans.type == TRADE_TRANSACTION_DEAL_ADD) {
        ulong dealTicket = trans.deal;
        if(HistoryDealSelect(dealTicket)) {
            ENUM_DEAL_ENTRY dealEntry = (ENUM_DEAL_ENTRY)HistoryDealGetInteger(dealTicket, DEAL_ENTRY);
            ENUM_DEAL_TYPE dealType = (ENUM_DEAL_TYPE)HistoryDealGetInteger(dealTicket, DEAL_TYPE);
            
            if(dealEntry == DEAL_ENTRY_IN) {
                double lots = HistoryDealGetDouble(dealTicket, DEAL_VOLUME);
                double price = HistoryDealGetDouble(dealTicket, DEAL_PRICE);
                
                WriteLog(LOG_LEVEL_INFO, StringFormat("新仓位开立: %s %.2f手 价格%.5f", 
                    EnumToString(dealType), lots, price));
                
                // 检查是否需要发出警告
                if((dealType == DEAL_TYPE_BUY && buyOrderCount >= 6) || 
                   (dealType == DEAL_TYPE_SELL && sellOrderCount >= 6)) {
                    string alertMessage = StringFormat("%s - %s单数量达到 %d 单，请注意盯盘！", 
                        _Symbol, (dealType == DEAL_TYPE_BUY) ? "买" : "卖", 
                        (dealType == DEAL_TYPE_BUY) ? buyOrderCount : sellOrderCount);
                    Alert(alertMessage);
                }
            }
        }
    }
} 